let loginInfo = require('../../login.js');
let app = getApp();
const { tabbar_type } = app.siteInfo;
const WxNotificationCenter = require('../../../common/utils/WxNotificationCenter/WxNotificationCenter');
WxNotificationCenter.postNotificationName(app.INJECT_BLOBAL_EVENT, {
  global: require('../../global'),
});
Page({
  data: {
    leng: 0,
    userInfo: {},
    memberInfo: {},
    defaultInfo: {},
    pageSet: [],
    photos: [],
    remark: [],
    comments: [],
    attachurl: app.siteInfo.attachment_url,
    param: {
      type: 2,
      default: 1,
    },
    start: 1,
    length: 5, // 首页只取最新5条
    title: '', // 分享转发标题
    path: '', // 分享转发路径
    imageUrl: '', // 分享转发图片
    desc: '', // 分享转发描述
    showTabbar: false
  },
  onLoad: function(options) {
    let showTabbar = this.shouldShowFixedMenu('cm_micro_single_page/pages/index/index');
    showTabbar && this.findActualHome();
    this.setData({ showTabbar, appJson: app.siteInfo.appJson });
    let that = this;
    let opts = options || {};
    that.setData({
      opts,
      themData: app.setThemeColor() || false,
    });
    app.util.getCurrentTabInfo().then(function(res) {
      that.setData({
        leng: app.siteInfo.appJson.length,
      });
    });
    if (options.id > 0 || wx.getStorageSync('fromid') > 0) {
      that.setData({
        param: {
          type: 2,
          default: 1,
          id: options.id ? options.id : wx.getStorageSync('fromid'),
        },
      });
    }
  },
  onShow() {
    this.loadInit();
  },
  loadInit: function() {
    let that = this;
    loginInfo.openidInfo(false).then(() => {
      that.loadDefault();
      that.loadSet();
      that.getShareAppMessage();
    });

  },
  // 获取默认微单页
  loadDefault: function() {
    let that = this;
    let parr = [];
    app.util.request({
      url: 'entry/wxapp/api',
      data: that.data.param,
      cachetime: '0',
      module: 'cm_micro_single_page',
      success(res) {
        for (let index in res.data.data.photo_list) {
          if (Object.prototype.hasOwnProperty.call(res.data.data.photo_list, index)) {
            parr.push(that.data.attachurl + res.data.data.photo_list[index]);
          }
        }
        that.setData({
          defaultInfo: res.data.data,
          photos: parr,
          remark: res.data.data.remark,
        });
        wx.setNavigationBarTitle({
          title: res.data.data.title || '',
        });
        // 设置当前单页id
        wx.setStorageSync('fromid', res.data.data.id);
        // 加载评论
        that.loadComment(res.data.data.id);
      },
      fail() {
        wx.showToast({
          title: '默认数据加载失败！',
        });
      },
    });
  },
  showPhotos: function() {
    wx.previewImage({
      current: '', // 当前显示图片的http链接
      urls: this.data.photos, // 需要预览的图片http链接列表
    });
  },
  // 获取店铺评价列表
  loadComment: function(pid) {
    let that = this;
    let start = that.data.start;
    let length = that.data.length;
    app.util.request({
      url: 'entry/wxapp/api',
      data: {
        type: 3,
        pid: pid,
        start: start,
        length: length,
      },
      module: 'cm_micro_single_page',
      cachetime: '0',
      success(res) {
        that.setData({
          comments: res.data.data,
        });
      },
      fail() {
        wx.showToast({
          title: '评价列表获取失败！',
        });
      },
    });
  },
  // 获取系统设置
  loadSet: function() {
    let that = this;
    app.util.request({
      url: 'entry/wxapp/api',
      data: {
        type: 0,
      },
      module: 'cm_micro_single_page',
      cachetime: '0',
      success(res) {
        that.setData({
          pageSet: res.data.data,
        });
      },
      fail() {
        wx.showToast({
          title: '系统信息设置失败！',
        });
      },
    });
  },
  // 企业列表
  showLists: function(e) {
    let pid = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '../list/list?pid=' + pid,
    });
  },
  // 评论页面
  goComment: function(e) {
    let pid = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '../comment/comment?pid=' + pid,
    });
  },
  phoneCall(e) {
    // 拨打电话
    let phoneNumber = e.currentTarget.dataset.tel;
    if (phoneNumber) {
      wx.makePhoneCall({
        phoneNumber,
      });
    }
  },
  goMap(e) {
    // 打开地图
    let lat = Number(e.currentTarget.dataset.lat);
    let lng = Number(e.currentTarget.dataset.lng);
    let title = e.currentTarget.dataset.title;
    let address = e.currentTarget.dataset.address;
    let QQMapWX = require('../../../common/utils/qqmap/qqmap-wx-jssdk.min.js');
    new QQMapWX({
      key: '3ESBZ-VPYWF-7Q7JL-NXY3M-4AVQT-T4BLE',
    }).reverseGeocoder({
      location: {
        latitude: lat,
        longitude: lng,
      },
      coord_type: 3, // baidu经纬度
      success: function(res) {
        let location = res.result.location;
        wx.openLocation({
          latitude: location.lat,
          longitude: location.lng,
          name: title,
          address: address,
          scale: 28,
        });
      },
      fail() {
        wx.showToast({
          title: '经纬度获取失败！',
        });
      },
    });
  },
  getShareAppMessage() {
    let _this = this;
    app.util.request({
      url: 'entry/wxapp/api',
      data: {
        type: 1,
      },
      module: 'cm_micro_single_page',
      cachetime: '0',
      success(res) {
        if (!res.data.data) return;
        let msg = res.data.data;
        msg.imageUrl = _this.data.attachurl + msg.imageUrl;

        _this.setData({
          title: msg.title, // 分享转发标题
          path: msg.path, // 分享转发路径
          imageUrl: msg.imageUrl, // 分享转发图片
          desc: msg.desc, // 分享转发描述
        });
      },
      fail() {
        wx.showToast({
          title: '分享数据获取失败！',
        });
      },
    });
  },
  onShareAppMessage(res) {
    // 统一分享
    let _this = this;
    let title = _this.data.title;
    let path = `cm_micro_single_page/${_this.data.path || 'pages/index/index'}`;
    let imageUrl = _this.data.imageUrl;
    let desc = _this.data.desc;
    if (res.from === 'button') {
      // 来自页面内转发按钮
    }
    return {
      title, // 分享转发标题
      path, // 分享转发路径
      imageUrl, // 分享转发图片
      desc, // 分享转发描述
      success: function(res) {
        // 转发成功
      },
    };
  },

  gotoHome(e) {
    let appJson = this.data.appJson;
    let moduleName = appJson[0].module;
    let tpl = app.siteInfo.template_num;
    let url = '';
    if (moduleName === 'ws_micro_company' && tpl) {
      url = moduleName + (tpl === '0' ? '_visual' : '_' + tpl) + '/pages/index/index';
    } else {
      url = appJson[0].homePage || appJson[0].tabBar.list[0].pagePath;
    }
    app.util.navigateTo(url);
  },

  shouldShowFixedMenu(pageUrl) {
    if (app.siteInfo.module === 'ws_empty') {
      return false;
    }
    let tabBars = [];
    let tabBarPages = [];
    let currentModuleIndex = app.tabbarindex;
    if (tabbar_type === '2') return true;
    if (app && app.tabInfo && app.tabInfo[currentModuleIndex] && app.tabInfo[currentModuleIndex].tabBar) {
      tabBars = app.tabInfo[currentModuleIndex].tabBar.list;
      tabBars.forEach(item => tabBarPages.push(item.pagePath));
    }
    if (tabBarPages.indexOf(pageUrl) !== -1) return false;
    else return true;
  },

  findActualHome() {
    let homeModule = app.siteInfo.appJson[0];
    let actualTab = homeModule.tabBar.list.find(item => item.pagePath === homeModule.homePage);
    actualTab && this.setData({ actualTab });
  },
});
